<?php

namespace app\controller;

use app\BaseController;
use app\Log;
use app\model\StationOil;
use app\model\StationPriceTask;
use think\facade\Db;

class Task extends BaseController
{
    public function stationTask(): \think\Response|\think\response\Redirect
    {
        $log = new Log("task/station");
        $taskModel = $this->app->make(StationPriceTask::class);
        $task = $taskModel->where('state', 1)->where('start_time', '<=', date('Y-m-d H:i:s'))->paginate([
            'list_rows' => 30,
            'page' => 1
        ])->toArray();
        $log->write(['task' => $task]);
        if (empty($task)) return $this->success($task);
        $Oil = $this->app->make(StationOil::class);
        $data = $task['data'];
        $ids = array_column($data, 'id');
        $taskModel->whereIn("id", $ids)->save(['state' => 3]);//修改任务为执行中
        foreach ($data as $value) {
            if (!empty($value['station_id'])) {
                $Oil->whereIn('station_id', $value['station_id'])->where('oil_name', $value['oil'])->update([
                    'offic_price' => $value['price'],
                    'gun_price' => Db::raw("{$value['price']} - `gun_discount`")
                ]);
            }
        }
        $taskModel->whereIn("id", $ids)->save(['state' => 2, 'verify_time' => date("Y-m-d H:i:s")]);//修改任务为执行中

        if (!empty($task['has_more'])) {
            return redirect("?page=1");
        }
        return $this->success($task);
    }
}
